package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.User;
import service.UserService;
import exception.LoginException;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        JSONObject object=null;
        User user=null;
        Response build=null;
        try {
            object = GetRequestJsonUtils.getRequestJsonObject(req);
            String usrString= object.getString("user");
            System.out.println(usrString);
            user=JSON.parseObject(usrString,User.class);
        }catch (Exception e){
            build=Response.build(ResponseCode.ERROR_PARAN);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
        UserService userService=new UserService();
        User userDB=null;
        try {
            userDB= userService.login(user);
            HttpSession session = req.getSession();
            session.setAttribute("user", userDB);
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            resp.addCookie(cookie);
            String url = null;
            if (userDB.getRole().equals("超级用户")) {
                url = "/admin/login/home.jsp";
            } else {
                url = "/client/myAccount.jsp";
            }
            build = Response.build(ResponseCode.SUCCESS_LOGIN, url);
        }catch (LoginException e){
            e.printStackTrace();
            build=Response.build(e.getResponseCode());
        }
        System.out.println("aaa");
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());
    }
}
